package Network

import (
	"SQL/util"
	"logs"
)

func deleteGroup(clientID string, args interface{}) (response *ServerResponse) {

	var code = Success
	var info = "success"
	var information interface{}
	defer func() {
		response = &ServerResponse{
			Method:  "/deleteGroup",
			Code:    code,
			Message: info,
			Result:  information,
		}
	}()

	parameterMap, ok := args.(map[string]interface{})
	if !ok {
		code = errInvalidEmptyArgs
		info = mInvalidEmptyArgs
		return
	}

	userID := clientID

	groupID, ok := parameterMap["groupID"].(string)
	if !ok {
		code = errInvalidID
		info = "From:deleteGroup:---groupID is null"
		return
	}

	info, code, ok = checkOutDeletGroup(userID, groupID)
	if !ok {
		return
	}

	info, code, _ = deleteGroupFromDB(groupID)
	return
}

func deleteGroupFromDB(id string) (string, int, bool) {
	info := "success"
	code := Success
	ok := true

	sql := "delete from objects where id = $1"

	result, err := util.Exec(sql, id)
	if err != nil {
		logs.Print("From:deleteGroupFromDB.Exec:---", err.Error())
		info = "From:deleteGroupFromDB.Exec:---error"
		ok = false
		code = errDBExecFailed
		return info, code, ok
	}
	rowsAffected, err := result.RowsAffected()
	if err != nil {
		logs.Print("From:deleteGroupFromDB.RowsAffected:---", err.Error())
		info = "From:deleteGroupFromDB.RowsAffected:---error"
		code = errRowsAffected
		ok = false
		return info, code, ok
	}
	if rowsAffected <= 0 {
		info = "From:deleteGroupFromDB.RowsAffected:---delete rows is 0"
		code = errDBExecFailed
		ok = false
		return info, code, ok
	}

	return info, code, ok

}

func checkOutDeletGroup(userID string, groupID string) (string, int, bool) {

	info := "success"
	code := Success
	ok := true

	ok, code, info = checkOutId(groupID)
	if !ok {
		info = "From:deleteGroup.checkOutDeletGroup:---groupID is invlid"
		return info, code, ok
	}

	ok, code, info = checkOutId(userID)
	if !ok {
		info = "From:deleteGroup.checkOutDeletGroup:---userID is invlid"
		return info, code, ok
	}

	info, code, ok = isGroup(groupID)
	if !ok {
		info = "From:deleteGroup.checkOutDeletGroup:---groupID is invlid because groupID is not group"
		return info, code, ok
	}

	info, code, ok = isOwner(userID, groupID)
	if !ok {
		info = "From:deleteGroup.checkOutDeletGroup:---userID is invlid because userID is not owner"
		return info, code, ok
	}

	return info, code, ok
}
